package club.banyuan.controller;

import club.banyuan.bean.User;
import club.banyuan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;

@Controller
public class LoginController {

    private UserService userService;

    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(Principal principal) {
        System.out.println(principal.getName());
        return "redirect:/admin";
    }

    private User getUser(String username, String password) {
        if (username != null && password != null) {
            return userService.getUserByNameAndPassword(username, password);
        }
        return null;
    }

    @GetMapping("/admin")
    public String admin(Principal principal) {
        String username = principal.getName();
        System.out.println(username);
        return "admin";
    }

    @RequestMapping("/register")
    public String register(@RequestParam(required = false) String name,
                           @RequestParam(required = false) String password,
                           @RequestParam(required = false) String email,
                           RedirectAttributes redirectAttributes) {
        if (name != null && password != null && email != null) {
            User user=new User();
            user.setName(name);user.setPassword(password);user.setEmail(email);
            Integer insertUserRet = userService.insertUser(user);
            if (insertUserRet != 1) {
                return "register";
            }
            redirectAttributes.addFlashAttribute("user", user);
            return "redirect:/admin";
        }
        return "register";
    }





}
